package com.leetcode.partition10;

import com.leetcode.common.TreeNode;

import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/8/1 10:48
 */
public class LC938二叉搜索树的范围和 {

    public static int rangeSumBST(TreeNode root, int low, int high) {
        return bfs(root, low, high);
    }

    public static void main(String[] args) {
        LinkedList<Integer> queue = new LinkedList<>();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }

    //bfs：二叉树的层序遍历
    private static int bfs(TreeNode root, int low, int high) {
        int sum = 0;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int currentLevelSize = queue.size();
            for (int i = 0; i < currentLevelSize; i++) {
                TreeNode node = queue.poll();
                if (low <= node.val && node.val <= high) sum += node.val;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return sum;
    }

    //递归法
    private static int method1(TreeNode root, int low, int high) {
        return recursion(root, low, high);
    }

    private static int recursion(TreeNode root, int low, int high) {
        if (root == null) return 0;
        int leftSum = recursion(root.left, low, high);
        int rightSum = recursion(root.right, low, high);
        int sum = leftSum + rightSum;
        if (low <= root.val && root.val <= high) {
            sum += root.val;
        }
        return sum;
    }
}
